package top.zerocn.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Objects;
import java.util.Properties;

public class ResourceOperator {

	private static File resourceFile;
	private static Properties properties = new Properties();

	static {
		// 获取文件
		resourceFile = new File(System.getProperty("user.dir") + "/src/top/zerocn/dao/user.properties");
//		resourceFile = new File(ResourceOperator.class.getResource("user.properties").getFile().replace("%20", " "));
		// 读取文件
		try (FileInputStream fileInputStream = new FileInputStream(resourceFile)) {
			properties.load(fileInputStream);
		} catch (FileNotFoundException e) {
			System.err.println("未找到user.properties文件\n" + e.getMessage());
		} catch (IOException e) {
			System.err.println("读取user.properties文件出错\n" + e.getMessage());
		}
	}

	/**
	 * 
	 * @param id
	 * @return
	 */
	public static boolean saveFile(String name) {
		properties.setProperty(name, name + ".properties");
		try {
			properties.store(new FileOutputStream(resourceFile), null);
			return true;
		} catch (FileNotFoundException e) {
			System.err.println("未找到user.properties文件\n" + e.getMessage());
			return false;
		} catch (IOException e) {
			System.err.println("写入user.properties文件出错\n" + e.getMessage());
			return false;
		}
	}

	/**
	 * 
	 * @param name
	 * @return
	 */
	public static File getFile(String name) {
		String fileName = properties.getProperty(name);
		if (Objects.isNull(fileName)) {
			return null;
		}
		return new File(System.getProperty("user.dir") + "/src/top/zerocn/dao/" + fileName);
//		return new File(ResourceOperator.class.getResource(fileName).getFile().replace("%20", " "));
	}
}
